
#include "rtthread.h"
#include <string.h>
#include "fcntl.h"
static void sdcard_dfs_test();

void sd_card_init()
{
	rt_device_t dev = rt_device_find("sd0");
	if (dev == RT_NULL)
	{
		rt_kprintf("SD card not detected!\r\n");
	}
	else
	{
		// 打印sd容量

		rt_kprintf("SD card detected OK!\r\n");

		struct rt_device_blk_geometry geometry;
		if (rt_device_control(dev, RT_DEVICE_CTRL_BLK_GETGEOME, &geometry) == RT_EOK)
		{
			uint64_t cap = (uint64_t)geometry.sector_count * (uint64_t)geometry.bytes_per_sector / 1048576LL;

			rt_kprintf("Sector size: %d bytes Sector_conunt: %d\r\n", geometry.bytes_per_sector, geometry.sector_count);
			rt_kprintf("Total size: %d MB   \r\n", (uint32_t)cap);
		}

		/* 尝试挂载 */
		if (dfs_mount("sd0", "/", "elm", 0, 0) != RT_EOK)
		{
			rt_kprintf("Mount failed, format...\r\n");
			if (dfs_mkfs("elm", "sd0") == RT_EOK)
			{
				dfs_mount("sd0", "/", "elm", 0, 0);
				rt_kprintf("format sd0!\r\n");
			}
		}
		else
		{
			rt_kprintf("\r\nMount device sd0  / FatFS (elmfat) OK\r\n");
			df("/");
			rt_thread_mdelay(10);
			sdcard_dfs_test();
		}
		rt_kprintf("\r\nuse cmd `df` check sd_size\r\n");
	}
}
Export(sd_card_init);

static void sdcard_dfs_test()
{
	rt_kprintf("\r\nsdcard_dfs_test...\n");

	char buf[] = "SD write test OK!";
	char read_buf[64];
	memset(read_buf, 0, 64);

	// 写入
	int fd = open("/test0.txt", O_WRONLY | O_CREAT);
	if (fd >= 0)
	{
		int len = write(fd, buf, sizeof(buf));
		close(fd);
		rt_kprintf("\r\nWrite:len=%d,txt=%s\r\n", len, buf);
	}
	else
	{
		rt_kprintf("Open file test.txt error.\r\n");
	}

	// 读取
	fd = open("/test0.txt", O_RDONLY | O_CREAT);
	if (fd >= 0)
	{
		int len = read(fd, read_buf, sizeof(read_buf));
		close(fd);
		rt_kprintf("\r\nRead :len=%d,txt=%s\r\n", len, read_buf);
	}
	else
	{
		rt_kprintf("open file test.txt error.\r\n");
	}
}
